﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GuiaAeropuerto.Resources;
using Microsoft.Phone.Maps.Controls;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using Windows.Devices.Geolocation;
using System.Device.Location;

namespace GuiaAeropuerto
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public  MainPage() 
        {
            InitializeComponent();
            ViewModel.GuiaAeropuertoViewModel vm = ContentPanel.Resources["ViewModel"] as ViewModel.GuiaAeropuertoViewModel;
            vm.responseReady += vm_responseReady;
            createLocator();
            configMap(vm);
        }

        private void configMap(ViewModel.GuiaAeropuertoViewModel vm)
        {
            if (vm.Cartografia == "Vias")
                Map.CartographicMode = MapCartographicMode.Road;
            if (vm.Cartografia == "Aereo")
                Map.CartographicMode = MapCartographicMode.Aerial;
            if (vm.Cartografia == "Hibrido")
                Map.CartographicMode = MapCartographicMode.Hybrid;
            if (vm.Cartografia == "Terreno")
                Map.CartographicMode = MapCartographicMode.Terrain;

            if (vm.Color == "Claro")
                Map.ColorMode = MapColorMode.Light;
            if (vm.Color == "Oscuro")
                Map.ColorMode = MapColorMode.Dark;
        }

        private async void createLocator()
        {
            Geolocator loc = new Geolocator();
            loc.MovementThreshold = 10;
            loc.DesiredAccuracyInMeters = 5;
            loc.PositionChanged += loc_PositionChanged;
            await loc.GetGeopositionAsync();

            //GeoCoordinateWatcher gw = new GeoCoordinateWatcher();
            //gw.MovementThreshold = 10;
            //gw.PositionChanged += gw_PositionChanged;
            //gw.Start();
        }

        void gw_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Dispatcher.BeginInvoke(() =>
            {

                //  Map.SetView(new System.Device.Location.GeoCoordinate() { Latitude = args.Position.Coordinate.Latitude, Longitude = args.Position.Coordinate.Longitude }, 10,MapAnimationKind.Parabolic);
                Map.Center = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);

            });
        }

        void loc_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
        {


          

            Dispatcher.BeginInvoke(() => {
                ViewModel.GuiaAeropuertoViewModel vm = ContentPanel.Resources["ViewModel"] as ViewModel.GuiaAeropuertoViewModel;
              //  Map.SetView(new System.Device.Location.GeoCoordinate() { Latitude = args.Position.Coordinate.Latitude, Longitude = args.Position.Coordinate.Longitude }, 10,MapAnimationKind.Parabolic);
                Map.Center = new GeoCoordinate(args.Position.Coordinate.Latitude, args.Position.Coordinate.Longitude);
                createLayers(vm.Aeropuertos);

            });

        }

        void vm_responseReady(object sender, ViewModel.AirportResponseReadyEventArg e)
        {
            List<ViewModel.Airport> aeropuertos = e.Result;
            createLayers(aeropuertos);

        }

        private void createLayers(List<ViewModel.Airport> aeropuertos)
        {
            if (aeropuertos == null)
                return;

            GuiaAeropuerto.ViewModel.Airport AeropuertoCercano = new ViewModel.Airport() ;
               Dispatcher.BeginInvoke(new Action(() =>
                {
           AeropuertoCercano =  aeropuertos[0];
            double distance=  Map.Center.GetDistanceTo(new GeoCoordinate(Double.Parse(AeropuertoCercano.LatitudeDegree),Double.Parse(AeropuertoCercano.LongitudeDegree)));
            foreach (var item in aeropuertos)
            {
                if (Map.Center.GetDistanceTo(new GeoCoordinate(Double.Parse(item.LatitudeDegree), Double.Parse(item.LongitudeDegree))) < distance)
                {
                    distance = Map.Center.GetDistanceTo(new GeoCoordinate(Double.Parse(item.LatitudeDegree), Double.Parse(item.LongitudeDegree)));
                    AeropuertoCercano = item;
                }
            }

                }));

            foreach (var item in aeropuertos)
            {

                Dispatcher.BeginInvoke(new Action(() =>
                {
                   // Map.Layers.Clear();

                    var mo = new MapOverlay();
                    if (item.AirportCode == AeropuertoCercano.AirportCode)
                    {
                        mo.Content = new Image() { Source = new BitmapImage(new Uri("http://flagpedia.net/data/flags/normal/" + item.CountryAbbrviation.ToLower() + ".png", UriKind.Absolute)), Width = 100, Height = 100 };
                    }
                    else
                    {
                        mo.Content = new Image() { Source = new BitmapImage(new Uri("http://flagpedia.net/data/flags/normal/" + item.CountryAbbrviation.ToLower() + ".png", UriKind.Absolute)), Width = 60, Height = 60 };
                    }
                    mo.GeoCoordinate = new System.Device.Location.GeoCoordinate(Double.Parse(item.LatitudeDegree), Double.Parse(item.LongitudeDegree));
                    MapLayer layer = new MapLayer();
                    layer.Add(mo);
                    Map.Layers.Add(layer);


                }));

            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/View/ConfigPage.xaml", UriKind.Relative));
            
        }

    }
}